package editor;

import org.springframework.beans.propertyeditors.PropertiesEditor;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.regex.Pattern;

/**
 * Created by cmy on 2019/2/20.
 */
public class MyDateEditor extends PropertiesEditor {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
         //如何判断text为 yyyy-MM-dd yyyy/MM/dd yyyy年MM月dd日
        try {
            DateFormat dateFormat = getDateFormat(text);
            setValue(dateFormat.parse(text));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public DateFormat getDateFormat(String text) throws Exception {
        SimpleDateFormat sdf=null;
        if(Pattern.matches("\\d{4}-\\d{2}-\\d{2}",text)){
            sdf=new SimpleDateFormat("yyyy-MM-dd");
        }else if(Pattern.matches("\\d{4}/\\d{2}/\\d{2}",text)){
            sdf=new SimpleDateFormat("yyyy/MM/dd");
        }else if(Pattern.matches("\\d{4}年\\d{2}月\\d{2}日",text)){
            sdf=new SimpleDateFormat("yyyy年MM月dd日");
        }else{
            throw new Exception("日期类型不正确！");
        }
        return sdf;
    }
}
